import { WebSocket, WebSocketServer } from "ws";
import { Task } from "./task";
import { control } from "./control";

export class Socket {
    private server!: WebSocketServer;
    private task = new Task();
    public init(port: number) {
        this.server = new WebSocket.Server({ port: port });
        this.server.on("connection", (socket: WebSocket, request: any) => {
            this.on_connection(socket, request);
        });
    }

    public on_connection(socket: WebSocket, request: any) {
        let url = request.url.split('?')[0].split('/');
        let route = url[url.length - 1]
        switch (route) {
            case "desktop": {
                this.task.start(socket);
                break;
            }
            case "control": {
                socket.on("message", (message, is_binary) => {
                    this.on_message(message);
                });
                break;
            }
        }

    }

    public on_message(message: any) {
        let data = JSON.parse(message) as WebsocketMessage;
        switch (data.type) {
            case MessageType.KeyboardEvent: {
                control.hand_keyboard(data.data);
                break
            }
            case MessageType.MouseEvent: {
                control.hand_mouse(data.data);
                break
            }
        }
    }

    public close() {
        this.server.close();
    }
}

/**
 * websocket消息
 */
export interface WebsocketMessage {
    /**数据 */
    data: any;
    /**消息类型 */
    type: MessageType;
    /**错误信息 */
    error?: string;
}

export enum MessageType {
    /**键盘事件 */
    KeyboardEvent = "keyboard-event",
    /**鼠标事件 */
    MouseEvent = "mouse-event",
    /**屏幕信息 */
    ScreenInfo = "screen-info"
}
